package com.example.wudi.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.example.wudi.entity.Router;
import com.example.wudi.res.Res;
import com.example.wudi.service.RouterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/router/")
public class RouterController {
    @Autowired
    private RouterService routerService;


    @GetMapping("findAll")
    @CrossOrigin
    public Res findAll(@RequestParam String id) {
        return Res.okLit("", routerService.findAll(id));
    }

    @GetMapping("findNoAll")
    @CrossOrigin
    public Res findANoll() {
        return Res.okLit("", routerService.findNoAll());
    }

    @GetMapping("findOne")
    @CrossOrigin
    public Res findOne(@RequestParam String id) {
        final Router router = routerService.finnOneById(id);

        if(router != null) {
            return Res.okLit("已经添加到工作台", router);
        } else  {
            return Res.nolit("添加到工作台失败", null);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("router:add")
    @PostMapping("add")
    @CrossOrigin
    public Res add(@RequestBody Router routers) {
        final int i = routerService.addRouter(routers);

        if(i > 0) {
            return Res.okLit("已经添加到工作台", i);
        } else  {
            return Res.nolit("添加到工作台失败", i);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("router:update")
    @PostMapping("update")
    @CrossOrigin
    public Res update(@RequestBody Router routers) {
        final int i = routerService.update(routers);

        if(i > 0) {
            return Res.okLit("更新成功", i);
        } else  {
            return Res.nolit("更新失败", i);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("router:delete")
    @PostMapping("delete")
    @CrossOrigin
    public Res delete(@RequestParam Long id) {
        final int i = routerService.delete(id);

        if(i == 1) {
            return Res.okLit("删除成功", i);
        }
        else if(i == 899) {
            return Res.nolit("该路由有子路由，若想删除请先删除其子路由", i);
        }
        else  {
            return Res.nolit("删除失败", i);
        }
    }
}
